import socket
import threading

def receive_messages(client_socket):
    while True:
        try:
            response = client_socket.recv(1024).decode()
            if not response:
                print("服务器已断开连接")
                break
            print("服务端发送的消息:", response)
        except Exception as e:
            print(f"接收消息时发生错误：{e}")
            break
    client_socket.close()

def send_messages(client_socket):
    while True:
        message = input("发送消息 (输入 'exit' 退出): ")
        if message.lower() == 'exit':
            client_socket.send(message.encode())
            break
        client_socket.send(message.encode())
    client_socket.close()

def start_client():
    host = "0.0.0.0"  # 替换为 QPython 的服务器的 IP 地址
    port = 0         # 替换为 QPython 的服务器的端口号

    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        client_socket.connect((host, port))
        print(f"已连接到服务器 {host}:{port}，可以开始发送消息")
    except ConnectionRefusedError:
        print(f"连接到 {host}:{port} 被拒绝，请检查服务器是否已启动并监听该端口。")
        return
    except Exception as e:
        print(f"连接时发生错误：{e}")
        return

    receive_thread = threading.Thread(target=receive_messages, args=(client_socket,))
    send_thread = threading.Thread(target=send_messages, args=(client_socket,))

    receive_thread.start()
    send_thread.start()

    receive_thread.join()
    send_thread.join()

if __name__ == "__main__":
    start_client()